<template>
  <div class="topBar">
    <div class="wrap flBox">
      <!-- 左盒子 -->
      <div class="left">欢迎来到叩丁狼积分商城</div>

      <!-- 右盒子 -->
      <div class="right">
        <ul>
          <li>
            <img :src="userInfo.headImg" alt="" class="userImg" />
            用户名：{{ userInfo.nickName }}
          </li>
          <li>我的积分：{{ userInfo.coin }}</li>
          <li>获取积分</li>
          <li>叩丁狼官网</li>
          <li @click="changeIsShowLoginModal(true)" v-if="!isLogin">登录</li>
          <li v-if="isLogin">
            <img src="../assets/img/cart.png" alt="" />
            购物车
            <span>{{ cartTotal }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState, mapActions } from "vuex";
import { PCLoginAPI } from "../request/api";
export default {
  // 使用钩子函数，当页面刷新时调用
  created() {
    // 等待页面刷新完成，通过$router.onReady(callback)获取参数
    this.$router.onReady(async () => {
      // console.log("--topBar-created", this.$route.query);
      // 如果地址栏有code，表示准备进行扫码登录
      // 向后端发起微信扫码登录请求
      let pathCode = this.$route.query.code;
      // 判断地址是否有code （有无被扫码成功）
      if (pathCode) {
        let res = await PCLoginAPI({
          code: pathCode,
        });
        console.log(res);

        if (res.code == 0) {
          // 扫码登录成功
          this.asyncChangeIsShowToastModal({
            flag: true,
            toastMsg: "扫码登录成功！",
            toastType: "success",
          });

          // 存储token
          localStorage.setItem("x-auth-token", res["x-auth-token"]);

          // 显示购物车图标
          this.changeIsLoginModal(true);

          // 恢复默认地址
          this.$router.push(this.$route.path);

          this.asyncChangeUserInfo();
        } else if (res.code == 400) {
          // 二维码失效 2分钟内有效
          // 调用提示框
          this.asyncChangeIsShowToastModal({
            flag: true,
            toastMsg: res.message,
            toastType: "warning",
          });
          // 打开登录框
          this.changeIsShowLoginModal(true);
          this.$emit("openWeChat");
        } else if (res.code == 407) {
          // 当前用户第一次扫码登录
          // 调用提示框
          this.asyncChangeIsShowToastModal({
            flag: true,
            toastMsg: "请使用手机号再登录一次！",
            toastType: "warning",
          });
          // 弹出手机号绑定框
          this.changeIsShowLoginModal(true);

          // 本地存储 获取的uuid
          localStorage.setItem("uuid", res.uuid);

          // 恢复默认地址
          this.$router.push(this.$route.path);
        }
        // this.asyncChangeIsShowToastModal({
        //   flag: true,
        //   toastMsg: "登录成功！",
        //   toastType: "success",
        // });
      } else {
        // 判断有无token
        let token = localStorage.getItem("x-auth-token");
        this.changeIsLoginModal(Boolean(token));

        // 没有token时恢复默认用户信息
        if (token) {
          this.asyncChangeUserInfo();
        } else {
          this.initUserInfo();
        }
      }
    });
  },

  computed: {
    ...mapState({
      isLogin: (state) => state.loginModal.isLogin,
      userInfo: (state) => state.userInfo.userInfo,
      cartTotal: (state) => state.userInfo.cartTotal,
    }),
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLoginModal: "loginModal/changeIsLoginModal",
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncChangeIsShowToastModal: "showToast/asyncChangeIsShowToastModal",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
  },

  // 监视地址，一旦改变就检查有无token
  // 方式一 监视
  // watch: {
  //   "$route.path": {
  //     handler(newVal, oldVal) {
  //       console.log(newVal, oldVal);
  //       let token = localStorage.getItem("x-auth-token");
  //       this.changeIsLoginModal(Boolean(token));
  //     },
  //   },
  // },

  // 方式二 组件重载
};
</script>

<style lang="less" scoped>
.topBar {
  height: 40px;
  background-color: #242b39;
  .flBox {
    display: flex;
    justify-content: space-between;
    color: #fff;
    .left {
      line-height: 40px;
      font-size: 14px;
      font-family: SourceHanSansSC;
      font-weight: 300;
      color: #fffefe;
    }
    .right {
      ul {
        display: flex;
        li {
          line-height: 40px;
          margin-left: 30px;
          font-size: 14px;
          font-family: SourceHanSansSC;
          font-weight: 300;
          color: #fffefe;
          display: flex;
          align-items: center;
          justify-content: center;

          cursor: pointer;

          &:last-child {
            width: 124px;
            background-color: #0a328e;
            img {
              width: 20px;
              height: 20px;
              margin-right: 8px;
            }
            span {
              display: inline-block;
              width: 22px;
              height: 22px;
              border-radius: 50%;
              background-color: #fd604d;
              line-height: 20px;
              text-align: center;
              margin-left: 8px;
            }
          }
          .userImg {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-right: 6px;
            // vertical-align: middle;
          }
        }
      }
    }
  }
}
</style>>